package com.qf.blog.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

@Service
public class FollowerService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // blog:follower:108 [time,107]
    private String followerKey = "blog:follower:%s";

    private String fansKey = "blog:fans:%s";

    public void followerUser(Integer loginUserId, Integer followerUserId) {
        String fkey = String.format(followerKey, loginUserId);
        String fskey = String.format(fansKey, followerUserId);

        ZSetOperations<String, String> zSetOperations = stringRedisTemplate.opsForZSet();

        // 1.判断当前用户是否已关注fuserId
        Long rank = zSetOperations.rank(fkey, followerUserId.toString());

        if (rank == null) {
            // 还没有的关注，关注列表+1，粉丝列表+1
            // 1.给关注列表设置用户
            stringRedisTemplate.opsForZSet().add(fkey, followerUserId.toString(), System.currentTimeMillis());
            // 2.给粉丝列表也要设置
            stringRedisTemplate.opsForZSet().add(fskey, loginUserId.toString(), System.currentTimeMillis());
        } else {
            // 已经关注了，那就取消,关注列表-1，粉丝-1
            stringRedisTemplate.opsForZSet().remove(fkey, followerUserId.toString());
            stringRedisTemplate.opsForZSet().remove(fskey, loginUserId.toString());
        }
    }

    /**
     * 获取用户的关注数量
     *
     * @param id
     * @return
     */
    public Long getUserFollowerSize(Integer id) {
        String key = String.format(followerKey, id);
        return stringRedisTemplate.opsForZSet().size(key);
    }

    public Long getUserFansSize(Integer id) {
        String key = String.format(fansKey, id);
        return stringRedisTemplate.opsForZSet().size(key);
    }

    // true:关注，false：没关注
    // null 没有关注 不为null 有关注
    public Boolean hasFollower(Integer uid, Integer fid) {
        String key = String.format(followerKey, uid);
        Long rank = stringRedisTemplate.opsForZSet().rank(key, fid.toString());
        return rank != null; // true --> != null --->关注
    }
}
